package com.itheima.stock.mq;

import com.github.benmanes.caffeine.cache.Cache;
import com.itheima.stock.pojo.vo.StockMessage;
import com.itheima.stock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class StockMessageListener {

    @Autowired
    private Cache<String,Object> caffeineCache;

    @Autowired
    private StockService stockService;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "innerMarketQueue",durable = "true"),
                    exchange = @Exchange(value = "stockExchange",durable = "true",type = ExchangeTypes.DIRECT),
                    key = "inner.market"
            )
    })
    public void receiveMarketMsg(StockMessage msg){
        //2.刷新本地缓存
        //2.1 将本地缓存置为无效
        caffeineCache.invalidate("innerMarketData");
        //主动更新缓存: 主动将旧缓存剔除，然后触发新数据更新-及时性比较强
        // 延迟缓存：主动剔除缓存，什么时候用，就什么时候触发缓存更新
        //2.2 重新去数据库加载最新缓存
        stockService.getIndexAll();
        //1.获取消息类型和发送事件，判断消息延迟时间，超过1分钟，则出发警告
        long diffTime= DateTime.now().getMillis()-new DateTime(msg.getCurTime()).getMillis();
        if (diffTime >= 60*1000){
            log.warn("接收股票采集时间: {}，延迟：{}毫秒",msg.getCurTime(),diffTime);
        }
    }
}
